<template>
    <el-drawer v-model="props.signalVisible2" size="900" :before-close="handleClose" class="signal-drawer">
        <template #header>
            <div class="signal-header">
                <h4>信号</h4>
                <!-- <div class="signal-header-btn">
                    <el-button class="mt20" type="primary" @click="addDomain">新增信号</el-button>
                    <div class="signal-num">共有<span class="red-text">{{ dynamicValidateForm.domains.length }}</span>个信号
                    </div>
                </div> -->
            </div>
        </template>
        <template #default>
            <el-alert title="备注：第一、信号名称要判重。第二、信号编码前半部分用分类名称、设备名称、厂家、设备型号的id组成，后半部分用序号001开头往后排" type="error" />
            <div class="signal-btn mt10">
                <el-button type="primary" icon="Plus" @click="showAddDialog">新增信号</el-button>
                <el-button type="primary" icon="Upload" @click="handleImport">导入</el-button>
                <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
                <el-button type="danger" icon="Delete" @click="handleBatchDelete"
                    :disabled="selectIdArr.length ? false : true">批量删除</el-button>
                <div class="signal-btn-num">共有<span class="red-text">200</span>个信号
                </div>
            </div>
            <el-table :data="tableData" style="width: 100%" border @selection-change="selectChange" :height="tableHeight">
                <el-table-column type="selection" align="center"></el-table-column>
                <el-table-column prop="name" label="信号名称"></el-table-column>
                <el-table-column prop="code" label="信号编码"></el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-popconfirm :title="`你确定要删除${row.name}?`" width="260px" @confirm="handleDelete(row.code)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <el-pagination class="mt10" v-model:current-page="pageNo" v-model:page-size="pageSize"
                :page-sizes="[5, 7, 9, 11]" :background="true" layout="prev, pager, next, jumper,->,sizes,total"
                :total="total" @current-change="getTableData" @size-change="handler" />

            <el-dialog v-model="dialogVisible" :title="title" :close-on-click-modal="false" width="400">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
                    <el-form-item label="信号名称" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="信号编码" prop="code">
                        <el-input v-model="ruleForm.code"></el-input>
                    </el-form-item> -->
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                    </span>
                </template>
            </el-dialog>

        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="handleClose"> 取 消</el-button>
                <!-- <el-button @click="resetForm(formRef)"></el-button> -->
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, reactive, ref, nextTick, onMounted, onBeforeUnmount } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus';
// 定义接收的属性类型
const props = defineProps({
    signalVisible2: {
        type: Boolean,
        required: true
    }
});
// 定义自定义事件类型
const emits = defineEmits(['closeSignal2']);
const handleClose = () => {
    emits('closeSignal2', false)
    console.log('emitsemits')
}

interface Signal {
    name: string;
    code: string;
}

const tableData = ref<Signal[]>([
    { name: '信号1', code: '001' },
    { name: '信号2', code: '002' },
    { name: '信号3', code: '003' },
]);
let selectIdArr = ref<Signal[]>([]);

//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
    selectIdArr.value = value;
}
//默认页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(5);
//用户总个数
let total = ref<number>(0);

//组件挂载完毕
onMounted(() => {
    getTableData();
    calculateTableHeight();
    window.addEventListener('resize', handleResize);
});
onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
})
const getTableData = async (pager = 1) => {
    //收集当前页码
    pageNo.value = pager;
    // let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keyword.value);
    // if (result.code == 200) {
    //     total.value = result.data.total;
    //     userArr.value = result.data.records;
    // }
}
//分页器下拉菜单的自定义事件的回调
const handler = () => {
    getTableData();
}

const tableHeight = ref(0); // 表格高度
// 计算表格高度的函数
const calculateTableHeight = () => {
    const windowHeight = window.innerHeight - 180; // 获取窗口高度
    const tableHeaderHeight = 40; // 表格头部高度
    const tablePaginationHeight = 60; // 表格分页高度
    const padding = 20; // 上下边距
    tableHeight.value = windowHeight - tableHeaderHeight - tablePaginationHeight - padding;
};

// 监听窗口大小变化，动态计算表格高度
const handleResize = () => {
    calculateTableHeight();
};


const title = ref('')
const dialogVisible = ref(false);
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<Signal>({ name: '', code: '' });
const rules = reactive<FormRules<Signal>>({
    name: [{ required: true, message: '请输入信号名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入信号编码', trigger: 'blur' }],
})
const handleClear = () => {
    nextTick(() => {
        ruleFormRef.value?.clearValidate()
    })
}
const showAddDialog = () => {
    handleClear()
    title.value = '新增信号'
    dialogVisible.value = true;
    ruleForm.name = '';
    ruleForm.code = '';
};

const handleEdit = (row: Signal) => {
    handleClear()
    title.value = '编辑信号'
    dialogVisible.value = true;
    ruleForm.name = row.name;
    ruleForm.code = row.code;
};

const handleDelete = (row: Signal) => {
    ElMessageBox.confirm('确定删除该信号吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        const index = tableData.value.indexOf(row);
        if (index !== -1) {
            tableData.value.splice(index, 1);
            ElMessage.success('删除成功');
        }
    });
};

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            dialogVisible.value = false;
        } else {
            console.log('error submit!', fields)
        }
    })
}
const handleImport = () => {
    // 处理导入逻辑
};

const handleExport = () => {
    // 处理导出逻辑
};

const handleBatchDelete = async () => {
    //整理批量删除的参数
    let idsList: any = selectIdArr.value.map(item => {
        return item.code;
    });
    console.log(idsList)
    //批量删除的请求
    // let result: any = await reqSelectUser(idsList);
    // if (result.code == 200) {
    //     ElMessage({ type: 'success', message: '删除成功' });
    //     getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    // }
};


</script>
<style lang="scss" scoped>
.signal-header-btn {
    display: flex;
    align-items: center;
}

.signal-num {
    font-size: 16px;
    margin-top: 15px;
    margin-left: 10px;
}

.red-text {
    color: #ff0000;
}

.signal-btn {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.signal-btn-num {
    margin-left: 10px;
}
</style>